package com.service;

import com.dao.OrderItemMapper;
import com.dao.OrderMapper;
import com.dao.TableMapper;
import com.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class OrderService {


    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private TableMapper tableMapper;


    @Autowired
    private OrderMapper orderMapper;

    public Order getOrder (Integer id) {
        OrderExample oExample = new OrderExample();
        OrderExample.Criteria criteria = oExample.createCriteria();
        criteria.andOIdEqualTo(id);
        OrderItemExample oiExample = new OrderItemExample();
        OrderItemExample.Criteria ancriteria = oiExample.createCriteria();
        ancriteria.andOIdEqualTo(id);
        List<Order> orders = orderMapper.selectByExampleWithTable(oExample);
        if (orders == null)
            return null;
        Order order =  orders.get(0);
        order.setOrderItems(orderItemMapper.selectByExampleWithDish(oiExample));
        return order;
    }

    //生成订单，原本的代码
//    public int addOrder (Order order) {
//        int id = (int) orderMapper.countByExample(null);
//        System.out.println(id);
//        order.setoId(id+1);
//        orderMapper.insertSelective(order);
//        return id+1;
//    }

    //添加订单，(need fix bug)
    public int addOrder(Integer tId, Integer dinersNum){
        Table oTable = tableMapper.selectByPrimaryKey(tId);
        String tStatus = oTable.gettStatus();  //餐桌状态

        if(tStatus.equals(TableStatus.EMPTY.getStatus())){
            Order order = new Order();  //初始化订单信息
            order.settId(tId);
            order.setoStatus(OrderStatus.UNPAID.getStatus()); //设置订单状态未付款,设置餐桌为已满
            order.setDinerNum(dinersNum); //设置用餐人数
            orderMapper.createOrder(order);
            //设置餐桌为在餐饮
            tableMapper.updateTableStatusById(TableStatus.FULL.getStatus(), tId);
            return orderMapper.selectOrderBySerialNo(order.getoSerialNo()).getoId();
        }

        return -1;
    }

    //删除订单，原本代码
//    public void deleteOrder (Integer id) {
//        OrderItemExample oiExample = new OrderItemExample();
//        OrderItemExample.Criteria criteria = oiExample.createCriteria();
//        criteria.andOIdEqualTo(id);
//        orderMapper.deleteByPrimaryKey(id);
//        orderItemMapper.deleteByExample(oiExample);
//    }



    //删除订单v2.0，联级删除orderitem中的内容, 同时设置餐桌的状态为空座，可以拼桌或者加单
    public void deleteOrder(Integer oId){
        Order order = orderMapper.selectOrderWithItems(oId);
        System.out.println("fix bug v1");
//        int tId = order.gettId(); //餐桌id
        List<OrderItem> orderItemList = order.getOrderItems();
        System.out.println("fix bug v2");

        //联级删除orderitem
        if(orderItemList!=null && orderItemList.size() != 0){
            for(OrderItem orderItem: orderItemList){
                orderItemMapper.deleteItemsByOrderId(orderItem.getoId());
            }
        }
        System.out.println("fix bug v3");


        //后删除order
        orderMapper.deleteOrder(order);

        System.out.println("fix bug v4");


        //餐桌变为空座
        tableMapper.updateTableStatusById(TableStatus.EMPTY.getStatus(), order.gettId());

        System.out.println("fix bug v5");



    }


    //挂单操作
    public void orderSuspend(Integer oId){
        Map<String,Object> map = new HashMap<>();
        map.put("oId", oId);
        map.put("oStatus", OrderStatus.SUSPENDED.getStatus());
        orderMapper.updateOrderStatus(map);
    }


    //算订单总数量
    public Integer getTotalQuantity(Integer oId){
        List<OrderItem> orderItemList = orderItemMapper.selectOrderItemByOid(oId);
        if(orderItemList.size() != 0){
            Integer totalQuantity = 0;
            for(OrderItem orderItem: orderItemList){
                totalQuantity += orderItem.getNum();
            }
            return totalQuantity;
        }
        return null;
    }


    //算出总金额
    public BigDecimal getTotalMoney(Integer oId){
        List<OrderItem> orderItemList = orderItemMapper.selectOrderItemByOid(oId);
        if(orderItemList.size()!=0){
            BigDecimal totalMoney = new BigDecimal("0.0");
            for(OrderItem orderItem: orderItemList){
                //总价等于 每一项的subtotal相加
                 totalMoney = totalMoney.add(orderItem.getOiSubtotal());
            }
            return totalMoney;
        }
        return null;
    }




    //更具oid查询数量和总价
    public Order selectPQbyOid(Integer oId){
        return orderMapper.selectPQbyOid(oId);
    }


    //根据oid查询订单项
    public Order selectOrderWithItems(Integer oId){
        return orderMapper.selectOrderWithItems(oId);
    }


    //结束订单
    public void finishOrderByOid(Integer oId){
        Order order = orderMapper.selectByPrimaryKey(oId);
        order.setoStatus(OrderStatus.PAID.getStatus());  //设置订单为已支付
        order.setoPayoffDate(new Date());  //设置结单时间
        orderMapper.updateByPrimaryKeySelective(order);  //更新订单信息
        //更新餐桌信息
        tableMapper.updateTableStatusById(TableStatus.EMPTY.getStatus(), order.gettId());

    }



    //    //算出余额
//    public BigDecimal getBalance(Payment payment){
////        if(payment.getpReceiptAmount() < getTotalMoney() )
//        return payment.getpReceiptAmount().subtract(getTotalMoney(payment.getoId()));
//    }




    //生成订单细则
//    public void addOrderItem (OrderItem orderItem) {
//        orderItemMapper.insertSelective(orderItem);
//    }

    //修改总价和小计... 需要修改
    public void updateOrder (Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    //根据订单状态查询订单
    public List<Order> selectAllByOrderStatus(String oStatus){
        return orderMapper.selectAllByOrderStatus(oStatus);
    }



    //加上这行、上面的空行、下面的代码
    // 得到所有的订单数据，因为不想改动XML文件，所以这里根据id进行二次查询,正式的使用中使用XML关联查询
    public List<Order> getAllOrder() {
//        return orderMapper.selectByExampleWithTable(null);
//        List<Order> orderList = orderMapper.selectByExampleWithTable(null);
//        for()

//        使用自定义的sql
        List<Order> orderList = orderMapper.selectAllOrderData();
        //格式化日期
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //修改日期格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String dateStr =  simpleDateFormat.format(orderList.get(0).getoDate());
//        Date mydate = simpleDateFormat.parse(dateStr);

        //这里暂时先局部异常处理，后期如果来得及可以全局异常处理
//        try{
//            Date mydate = simpleDateFormat.parse(dateStr);
//            System.out.println("######-----  "+mydate +"  日期格式");
//        }catch(Exception ex){
//            ex.printStackTrace();
//        }
//
//        for(Order order: orderList){
//
//        }

        System.out.println("service的getAllOrder方法日期类型为为："+ orderList.get(0).getoDate().getClass().getName()+" 此处为日期格式");


        return orderList;

    }

    //
}
